package com.itheima.reggie.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.service.ICategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;


/**
 * 分类管理
 */
@RestController
@RequestMapping("/category")
public class CategoryController {
    @Autowired
    private ICategoryService categoryService;

    /**
     * 新增分类
     * @return
     */
    @PostMapping
    public R save(HttpSession session, @RequestBody Category category){
//        category.setCreateTime(LocalDateTime.now());
//        category.setUpdateTime(LocalDateTime.now());
//        Employee loginUser = (Employee) session.getAttribute("loginUser");
//        category.setUpdateUser(loginUser.getId());
//        category.setCreateUser(loginUser.getId());
        //1、调用业务层保存 employee数据
        boolean save = categoryService.save(category);
        //2、返回结果R
        if (save) {
            return R.success(null);
        }else {
            return R.error("新增失败");
        }
    }

    /**
     * 分页查询
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/page")
    public R page(Integer page,Integer pageSize){
        Page<Category> pageInfo = new Page<>(page, pageSize);
        LambdaQueryWrapper<Category> qw=new LambdaQueryWrapper<>();
        qw.orderByAsc(Category::getSort);
        categoryService.page(pageInfo, qw);
        return R.success(pageInfo);
    }

    /**
     * 删除分类
     * @param id
     * @return
     */
    @DeleteMapping()
    public R delete(Long id){
        categoryService.removeById(id);
        return R.success("删除成功");
    }

    /**
     * 修改分类
     * @param category
     * @return
     */
    @PutMapping
    public R update(@RequestBody Category category){
        categoryService.updateById(category);
        return R.success("修改成功");
    }

    /**
     * 菜品分类
     * @param type
     * @return
     */
    @GetMapping("/list")
    public R list(Integer type){
        //构造器
        LambdaQueryWrapper<Category> qw = new LambdaQueryWrapper<>();
        //条件
        qw.eq(type !=null,Category::getType,type);
        qw.orderByDesc(Category::getSort);
        List<Category> list = categoryService.list(qw);
        return R.success(list);
    }
}
